import os
import sys
import django
import datetime
from dateutil.relativedelta import relativedelta

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'finance_c2c.settings'
django.setup()
from apps.coffee.models import CouponMake, CouponInfo, GiveRecord
from django.contrib.auth import get_user_model

User = get_user_model()


# 每天生成券
def everyday_make_coupon():
    now_day = datetime.date.today()
    now_time = datetime.datetime.now()

    week_day = datetime.date.today().weekday() + 1  # 0，1，2，3，4，5，6
    print(week_day)

    queryset = CouponMake.objects.filter(everyday_make=True, make_expire_time__gte=now_day)
    print(now_time)
    for i in queryset:
        weeks_int_list = [int(i) for i in i.weeks.split(",")]
        # 增加星期几
        if week_day in weeks_int_list:
            num = i.num
            if i.expire_day:
                expire_time = i.expire_day
            else:
                expire_time = now_day + relativedelta(days=i.expire_time)
            user = User.objects.get(mobile=i.mobile)
            coupon_queryset = CouponInfo.objects.filter(user=user, everyday_make=True, used=False)
            # make_num = num - coupon_queryset.count()
            # if make_num > 0:
            #     print(i.num)
            #     CouponInfo.objects.bulk_create_by_normal(num, i.name, user, i.channel, expire_time,
            #                                              now_time, i.c_type, quota=i.quota, everyday_make=True)
            # 直接添加当天的数据
            CouponInfo.objects.bulk_create_by_normal(num, i.name, user, i.channel, expire_time,
                                                     now_time, i.c_type, quota=i.quota, everyday_make=True)
            # 更新没用完的券的有效期
            coupon_queryset.update(expire_time=expire_time, expired=False)


if __name__ == '__main__':
    everyday_make_coupon()
